//index.js
//获取应用实例
const app = getApp();
let { api, imgUrl } = require("./../../utils/api.js");
let { getTime, randomVal } = require("./../../utils/constant.js");
let uploadImgs = [];
let placeArr = [
  "哇喔~，这个菜真是 . . .",
  "我的天，今个菜品让我 . . .",
  "可输入300字以内的评价 . . .",
  "嗝~~,不错不错，整个 . . .",
  "请输入您对本餐厅的整体评价"
];

Page({
  /**
   * 页面的初始数据
   */
  data: {
    textNum: 0, //显示输入的文字内容长度
    placeholder: randomVal(placeArr), //输入框的提示文案
    Images: [], // 上传的照片
    chooseLevel: 5, // 评级, 默认为5（超赞）
    iptEvaluates: "", // 输入的数据
    anonymous: false, // 初始是否匿名
    items: [
      { name: 5, value: "超赞" },
      { name: 4, value: "良好" },
      { name: 3, value: "一般" },
      { name: 2, value: "不喜欢" },
      { name: 1, value: "差" }
    ],
    zan1: "fa fa-thumbs-o-up",
    zan2: "fa fa-thumbs-o-up zan-icon",
    imgUrl,
    damoHeight: "100",
    arry: [] // 控制图片懒加载
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {},

  onShow: function() {
    // 获取所有餐厅评价数据
    this.getEveluatesData();
  },

  onPullDownRefresh: function() {
    //下拉刷新数据
    // 获取所有餐厅评价数据
    this.getEveluatesData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: "成功加载最新评价 ！",
        icon: "none",
        duration: 2000
      });
    }, 1500);
  },

  // 监听用户滑动页面事件。
  onPageScroll: function(res) {
    var that = this;
    var str = parseInt(res.scrollTop / that.data.damoHeight);
    that.data.arry[str] = true;
    that.setData({
      arry: that.data.arry
    });
  },
  // 初始化评论图片懒加载的显示数组arry
  loadArry: function(data) {
    let arry = [];
    let num = Math.ceil(wx.getSystemInfoSync().windowHeight / 300);
    for (let i = 0; i < data.length; i++) {
      i < num ? arry.push(true) : arry.push(false);
    }
    this.setData({
      arry
    });
  },
  //获取所有餐厅评价数据
  getEveluatesData: function() {
    if (wx.getStorageSync("userInfo").userId) {
      let that = this;
      let obj = {
        userId: wx.getStorageSync("userInfo").userId
      };
      wx.request({
        url: api + "getRestaurantEvaluation.do",
        method: "POST",
        data: obj,
        success: function(res) {
          // console.log(res.data.data);
          console.log("发布餐厅评价：我刷新了！");
          if (res.data.status === 1) {
            that.loadArry(res.data.data);
            let hotComment = [];
            let newComment = res.data.data.map(val => {
              // 截取08-09 12:00格式的日期
              val.evaluationRestaurant.evaluationDate = val.evaluationRestaurant.evaluationDate.slice(
                5,
                17
              );
              // 解码评价文本（应对可能出现表情的情况）
              val.evaluationRestaurant.evaluationContent = decodeURIComponent(
                val.evaluationRestaurant.evaluationContent
              );
              if (val.evaluationRestaurant.likesnum >= 10) {
                hotComment.push(val);
              }
              return val;
            });
            that.setData({
              allComment: [hotComment, newComment]
            });
          } else {
            wx.showToast({
              title: "评价获取失败，请稍后重试!",
              icon: "none",
              duration: 2000
            });
          }
        },
        fail: function(res) {
          wx.showToast({
            title: "网络错误，请稍后重试",
            icon: "none",
            duration: 2000
          });
        }
      });
    }
  },
  // 点击图片进行放大
  imgPreview: function(e) {
    let src = e.currentTarget.dataset.src;
    let srcArr = [src];
    let current = src;
    if (Object.prototype.toString.call(src) == "[object Array]") {
      srcArr = src.map(val => {
        return imgUrl + val;
      });
      current = e.currentTarget.dataset.current;
    }
    wx.previewImage({
      current,
      urls: srcArr // 需要预览的图片http链接列表
    });
  },
  // 评论点赞
  changZan: function(e) {
    let { allComment } = this.data;
    let newAllComment = allComment;
    //页面展示已经点赞（取消赞）的操作（假象）
    for (let val of newAllComment[1]) {
      if (
        val.evaluationRestaurant.evaluationId === Number(e.currentTarget.id)
      ) {
        val.evaluationRestaurant.isIlike
          ? val.evaluationRestaurant.likesnum--
          : val.evaluationRestaurant.likesnum++;
        val.evaluationRestaurant.isIlike = !val.evaluationRestaurant.isIlike;
      }
    }
    this.setData({
      allComment: newAllComment
    });
    //真是的进行接口点赞操作后台处理
    wx.request({
      url: api + "likRestaurantEvaluation.do",
      method: "POST",
      data: {
        userId: wx.getStorageSync("userInfo").userId,
        evaluationId: e.currentTarget.id
      },
      success: function(res) {
        if (res.data.status === 1) {
          let text = res.data.message === "取消赞成功" ? "已取消" : "已点赞";
          wx.showToast({
            title: text,
            icon: "none",
            duration: 2000
          });
        } else {
          wx.showToast({
            title: "我在开小差，请稍后再试！",
            icon: "none",
            duration: 2000
          });
        }
      },
      fail: function(res) {
        wx.showToast({
          title: "网络请求错误，请稍后再试！",
          icon: "none",
          duration: 2000
        });
      }
    });
  },

  // 选择图片上传
  chooseImages: function() {
    const that = this;
    wx.chooseImage({
      count: 6, //最多6张
      sourceType: ["album", "camera"],
      success: function(res) {
        console.log(res.tempFilePaths);
        that.setData({
          Images: res.tempFilePaths
        });
      },
      fail: function(res) {
        console.log(res);
      },
      complete: function(res) {}
    });
  },

  // 获取radio选择框
  radioChange: function(e) {
    // console.log(typeof(e.detail.value));
    this.setData({
      chooseLevel: Number(e.detail.value)
    });
  },

  // 获取输入评价
  inputEvaluates: function(e) {
    this.setData({
      iptEvaluates: e.detail.value,
      textNum: e.detail.value.length
    });
  },

  // 是否匿名
  isAnonymous: function(e) {
    this.setData({
      anonymous: !this.data.anonymous
    });
  },

  // 发布所有评价信息
  releaseEvaluates: function() {
    let that = this;
    let { chooseLevel, iptEvaluates, anonymous } = this.data;
    let obj = {
      userId: wx.getStorageSync("userInfo").userId,
      evaluationContent: encodeURIComponent(iptEvaluates),
      evaluationScore: chooseLevel,
      evaluationPhotoList: uploadImgs,
      anonymous: anonymous ? 1 : 0,
      evaluationDate: getTime(1)
    };
    console.log(obj);
    wx.request({
      url: api + "addRestaurantEvaluation.do",
      method: "POST",
      data: obj,
      success: function(res) {
        console.log(res.data);
        // 关闭上传图片loading的提示框
        wx.hideLoading();
        if (res.data.status === 1) {
          wx.showToast({
            title: "发布成功",
            icon: "success",
            duration: 2000
          });
          wx.navigateTo({
            url: "../completeEvaluation/completeEvaluation"
          });
          // 清空之前填写的数据
          that.setData({
            Images: [], // 上传的照片
            chooseLevel: 5, // 评级, 默认为5（超赞）
            iptEvaluates: "", // 输入的评价信息
            anonymous: false
          });
          uploadImgs = [];
          that.getEveluatesData();
        } else {
          wx.showToast({
            title: "发布失败，请稍后重试!",
            icon: "none",
            duration: 2000
          });
        }
      },
      fail: function(res) {
        wx.showToast({
          title: "网络错误，请稍后重试",
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  //上传服务器图片，获取相应的路径
  uploadDIY: function(filePaths, i, length) {
    wx.uploadFile({
      url: api + "upload.do",
      filePath: filePaths[i],
      name: "fileData",
      success: res => {
        let newRes = JSON.parse(res.data);
        if (newRes.status === 1) {
          uploadImgs.push(newRes.data[0]);
        }
        if (i === length - 1) {
          //上传所有评价信息
          this.releaseEvaluates();
        }
      },
      fail: res => {
        wx.showToast({
          title: "图片上传失败，请重试!",
          icon: "none",
          duration: 2000
        });
      },
      complete: () => {
        i++;
        if (i !== length) {
          //递归调用uploadDIY函数
          this.uploadDIY(filePaths, i, length);
        }
      }
    });
  },
  // 提交评价
  submitEvaluates: function() {
    if (wx.getStorageSync("userInfo").userId) {
      let that = this;
      let { Images, iptEvaluates } = this.data;
      if (iptEvaluates != "") {
        if (Images.length > 0) {
          uploadImgs = [];
          wx.showLoading({
            title: "图片上传中!"
          });
          this.uploadDIY(Images, 0, Images.length);
        } else {
          this.releaseEvaluates();
        }
      } else {
        wx.showToast({
          title: "请输入评价信息！",
          icon: "none",
          duration: 1000
        });
      }
    } else {
      wx.showToast({
        title: "hi,请先登录哟 !",
        icon: "none"
      });
    }
  }
});
